#include "../header/datagram.hpp"

#include "../header/common_conf.hpp"

// make a datagram with type;
Datagram::Datagram(datagram_type type):header(type) {
    memset(data_buffer,0,sizeof(data_buffer));
}

// make a datagram with the buffer which is a datagram
Datagram::Datagram(char* buffer):header(buffer) {
    // memset(data_buffer,0,sizeof(data_buffer));
    
    // MLOG("generate datagram sign 1:"<<header.dataLength);
    memcpy(data_buffer,buffer+header_size,header.dataLength);
    // MLOG("generate datagram sign 2");
}

// input data to generate a datagram for transmit
bool Datagram::fillData(char* dataBuffer, int data_size,int seq) {
    if(data_size>msg_onePieceSize){
        MLOG("ERROR in fill data");
        return false;
    }
        

    header.dataLength = data_size;
    header.seqNum = seq;
    header.follow = 0;
    memcpy(this->data_buffer,dataBuffer,sizeof(char)*data_size);
    // MLOG("filled "<<header.dataLength);
    return true;
}

// get the datagram
// of course with the datagram data size return
int Datagram::get(char* buffer){
    header.get(buffer);
    // cout<<"debgu:"<<data_buffer<<endl;
    memcpy(buffer + header_size, data_buffer,sizeof(char)*header.dataLength);
    // cout<<"debug:"<<buffer+header_size<<endl;
    return header_size+header.dataLength;
}

// get the datagram's header
// of course with the datagram data size return
datagram_header& Datagram::getHeader(){
    return header;
}

// get the datagram's data
// of course with the datagram data size return
int Datagram::getData(char* buffer){
    memcpy(buffer,data_buffer,header.dataLength);

    return header.dataLength;
}